#include "Optimizer.h"
#include <iostream>
#include <sstream>

// ==================== ConstantFoldingOptimizer 实现 ====================

bool ConstantFoldingOptimizer::isConstant(ASTNode* node) {
    if (!node) return false;
    
    if (node->type == "NumLiteral") {
        return true;
    }
    
    if (node->type == "AddExpr" || node->type == "MulExpr") {
        return node->children.size() == 2 && 
               isConstant(node->children[0].get()) && 
               isConstant(node->children[1].get());
    }
    
    return false;
}

int ConstantFoldingOptimizer::evaluateConstant(ASTNode* node) {
    if (!node) return 0;
    
    if (node->type == "NumLiteral") {
        return std::stoi(node->value);
    }
    
    if (node->type == "AddExpr" || node->type == "MulExpr") {
        int left = evaluateConstant(node->children[0].get());
        int right = evaluateConstant(node->children[1].get());
        
        if (node->value == "+") {
            return left + right;
        } else if (node->value == "-") {
            return left - right;
        } else if (node->value == "*") {
            return left * right;
        } else if (node->value == "/") {
            return right != 0 ? left / right : 0;
        } else if (node->value == "%") {
            return right != 0 ? left % right : 0;
        }
    }
    
    return 0;
}

void ConstantFoldingOptimizer::optimize(ASTNode* root) {
    if (!root) return;
    optimizeNode(root);
}

void ConstantFoldingOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;
    
    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }
    
    // 检查是否可以常量折叠
    if (isConstant(node)) {
        int value = evaluateConstant(node);
        
        // 替换当前节点
        node->type = "NumLiteral";
        node->value = std::to_string(value);
        node->children.clear();
        
        std::cerr << "Constant folding: " << value << std::endl;
    }
}

// ==================== CommonSubexpressionOptimizer 实现 ====================

std::string CommonSubexpressionOptimizer::getExpressionKey(ASTNode* node) {
    if (!node) return "";
    
    std::ostringstream oss;
    oss << node->type;
    
    if (!node->value.empty()) {
        oss << ":" << node->value;
    }
    
    for (const auto& child : node->children) {
        oss << "(" << getExpressionKey(child.get()) << ")";
    }
    
    return oss.str();
}

void CommonSubexpressionOptimizer::optimize(ASTNode* root) {
    if (!root) return;
    expressionMap.clear();
    optimizeNode(root);
}

void CommonSubexpressionOptimizer::optimizeNode(ASTNode* node) {
    if (!node) return;
    
    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }
    
    // 检查是否是表达式节点
    if (node->type == "AddExpr" || node->type == "MulExpr" || 
        node->type == "RelExpr" || node->type == "UnaryExpr") {
        
        std::string key = getExpressionKey(node);
        
        // 检查是否已经存在相同的表达式
        auto it = expressionMap.find(key);
        if (it != expressionMap.end()) {
            // 找到公共子表达式，可以重用
            std::cerr << "Common subexpression found: " << key << std::endl;
            // 这里可以实现更复杂的替换逻辑
        } else {
            // 记录这个表达式
            expressionMap[key] = node;
        }
    }
}

// ==================== DeadCodeEliminator 实现 ====================

bool DeadCodeEliminator::isDeadCode(ASTNode* node) {
    if (!node) return false;
    
    // 检查是否是未使用的变量声明
    if (node->type == "DeclAssignStmt") {
        // 简单实现：假设所有声明都有用
        return false;
    }
    
    // 检查是否是未使用的表达式语句
    if (node->type == "Expr") {
        return !hasSideEffects(node);
    }
    
    return false;
}

bool DeadCodeEliminator::hasSideEffects(ASTNode* node) {
    if (!node) return false;
    
    // 函数调用有副作用
    if (node->type == "FuncCall") {
        return true;
    }
    
    // 赋值语句有副作用
    if (node->type == "AssignStmt") {
        return true;
    }
    
    // 递归检查子节点
    for (const auto& child : node->children) {
        if (hasSideEffects(child.get())) {
            return true;
        }
    }
    
    return false;
}

void DeadCodeEliminator::optimize(ASTNode* root) {
    if (!root) return;
    optimizeNode(root);
}

void DeadCodeEliminator::optimizeNode(ASTNode* node) {
    if (!node) return;
    
    // 先优化子节点
    for (auto& child : node->children) {
        optimizeNode(child.get());
    }
    
    // 检查是否是死代码
    if (isDeadCode(node)) {
        std::cerr << "Dead code elimination: " << node->type << std::endl;
        // 这里可以实现删除死代码的逻辑
        // 由于AST结构复杂，实际删除需要更复杂的处理
    }
}

// ==================== Optimizer 实现 ====================

void Optimizer::optimize(ASTNode* root) {
    if (!root) return;
    
    std::cerr << "Starting optimization..." << std::endl;
    
    // 应用各种优化
    optimizeConstantFolding(root);
    optimizeCommonSubexpressions(root);
    optimizeDeadCodeElimination(root);
    
    std::cerr << "Optimization completed." << std::endl;
}

void Optimizer::optimizeConstantFolding(ASTNode* root) {
    std::cerr << "Applying constant folding optimization..." << std::endl;
    constantFolder.optimize(root);
}

void Optimizer::optimizeCommonSubexpressions(ASTNode* root) {
    std::cerr << "Applying common subexpression elimination..." << std::endl;
    cseOptimizer.optimize(root);
}

void Optimizer::optimizeDeadCodeElimination(ASTNode* root) {
    std::cerr << "Applying dead code elimination..." << std::endl;
    deadCodeEliminator.optimize(root);
} 